package model

import (
	"sort"
	"strconv"
	"time"
)

// Conversation 文章
type Conversation struct {
	Id         int       `xorm:"INT(11) PK AUTOINCR comment('主键')" json:"id"`
	UserId     int       `xorm:"INT(11) comment('uid')" json:"user_id"`
	Status     int       `xorm:"INT(11) comment('1-normal，2-not-normal')" json:"status"`
	Prompt     string    `xorm:"TEXT comment('提问')" json:"prompt"`
	Completion string    `xorm:"MEDIUMTEXT comment('回复')" json:"completion"`
	User       *User     `xorm:"-" json:"user"` //分类
	Created    time.Time `xorm:"DATETIME INDEX" json:"created"`
	Updated    time.Time `xorm:"DATETIME" json:"updated"`
}

// ConversationGet  单条
func ConversationGet(id int) (*Conversation, bool) {
	mod := &Conversation{}
	has, _ := db.ID(id).Get(mod)
	return mod, has
}

// ConversationUidGet 单条用户信息
func ConversationUidGet(uid int) (*Conversation, bool) {
	mod := &Conversation{}
	has, _ := db.Where("user_id = ?", uid).Get(mod)
	return mod, has
}

// ConversationAll 所有
func ConversationAll(userId int, historyLimit int) ([]Conversation, error) {
	mods := make([]Conversation, 0, 4)
	sess := db.NewSession()
	defer sess.Close()

	if userId > 0 {
		sess.Where("user_id = ?", userId)
	}
	sess.Where("CHAR_LENGTH(CONCAT(prompt,completion)) < ?", 300)
	sess.Where("LEFT(completion, 10) <> ?", "data:image")
	sess.Where("TO_DAYS(created) = TO_DAYS(now()) ")
	err := sess.Desc("id").Limit(historyLimit).Find(&mods)
	//err := db.Desc("created").Find(&mods)

	sort.SliceStable(mods, func(i, j int) bool {
		return true
	})

	return mods, err
}

func ConversationGet1(id interface{}) (*Conversation, bool) {
	mod := &Conversation{}
	switch val := id.(type) {
	case int:
		has, _ := db.ID(val).Get(mod)
		return mod, has
	case string:
		has, _ := db.Where("prompt = ?", val).Get(mod)
		return mod, has
	default:
		return mod, false
	}
}

// ConversationPage

// ConversationCount PostCount 返回总数
func ConversationCount() int {
	mod := &Conversation{}
	sess := db.NewSession()
	defer sess.Close()
	count, _ := sess.Count(mod)
	return int(count)
}

// ConversationEdit PostEdit 编辑文章
func ConversationEdit(mod *Conversation, cols ...string) error {
	sess := db.NewSession()
	defer sess.Close()
	sess.Begin()
	if _, err := sess.ID(mod.Id).Cols(cols...).Update(mod); err != nil {
		sess.Rollback()
		return err
	}
	sess.Commit()
	return nil
}

// ConversationAdd PostAdd 添加
func ConversationAdd(mod *Conversation) error {
	sess := db.NewSession()
	defer sess.Close()
	sess.Begin()
	if _, err := sess.InsertOne(mod); err != nil {
		sess.Rollback()
		return err
	}
	sess.Commit()
	return nil
}

// ConversationDrop PostDrop 删除单条文章
func ConversationDrop(id int) error {
	sess := db.NewSession()
	defer sess.Close()
	sess.Begin()
	if _, err := sess.ID(id).Delete(&Conversation{}); err != nil {
		sess.Rollback()
		return err
	}
	sess.Commit()
	db.ClearCacheBean(&Conversation{}, strconv.Itoa(id))
	return nil
}

// ConversationIds PostIds 通过id集合返回文章
func ConversationIds(ids []int) map[int]*Conversation {
	mods := make([]Conversation, 0, len(ids))
	db.Cols("id", "title", "path", "cate_id", "created", "summary").In("id", ids).Find(&mods)
	mapSet := make(map[int]*Conversation, len(mods))
	for idx := range mods {
		mapSet[mods[idx].Id] = &mods[idx]
	}
	return mapSet
}
